<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/9/1
 * Time: 13:43
 * 表单上传控制器
 */
//define("DIR", "upload/");
//$file = $_FILES['file_stu'];
require 'env.php';
require 'pdo.php';
$req = $_REQUEST;
if ($req['fs'] == '2') {//批量导入

} else {
    if (!$req["content"]) {
        exit("亲耐的用户：单号不能为空");
    } else {
        $content_array = preg_split('/[,\r\n]+/s', $req['content']);
        if (!$content_array) {
            exit("亲耐的用户：单号格式有问题，请检查后重新输入");
        }

        if (count($content_array) > 20) {
            //存入数据库，然后脚本去轮询
            //不管是直接输入的  还是导入的csv都先存入数据库，这样方便脚本轮训的时候处理起来比较快速
            $ret = save_data($content_array);
            if (!$ret) {
                exit("保存失败");
            }
            exit("亲耐的用户：由于数据较大，超过20个单号的查询请申请查询之后的24小时访问<a href=''></a>系统查看");
        } else {

            foreach ($content_array as $cont) {
                if (empty($cont)) {
                    continue;
                }

                $no_html = http_get(trim($cont));//发送请求

                //因为不是数据接口，所以返回的是个html页面 所以要来抓取页面里面的东西
                $zz_res = format_html($no_html, trim($cont));

                $nzz[0] = $zz_res[0];
                $nzz[1] = $zz_res[1];
                $nzz[2] = $zz_res[2];
                $nzz[3] = $zz_res[3];


                $nos[] = $nzz;
            }
        }
    }
}
//::TODO 后续再加
//存储文件，然后读取里面数据
//    $file_array = explode(".", $file['name']);
//    $file_extension = strtolower(array_pop($file_array));
//    if ($file_extension != 'xls' || $file_extension != 'xlsx') {
//        exit("不是标准的xls文件");
//    }
//
//    //直接读取

function save_data($data)
{
    foreach ($data as $d) {
        $new_data['num'] = $d;
        $new_data['createtime'] = date('Y-m-d H:i:s');
        $newDatas[] = $new_data;
    }

    $result = mysql_mulit_insert('id_nums', $newDatas);
    return $result;

}


function mysql_mulit_insert($table, $arrData)
{
    $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST . ';port=' . DB_PORT;
    $user = DB_USER;
    $password = DB_PWD;
    $dbh = new PDO($dsn, $user, $password);
    $dbh->query("set names utf8");
    $name = $values = '';
    $flag = $flagV = 1;
    $true = is_array(current($arrData));//判断是否一次插入多条数据
    if ($true) {
        //构建插入多条数据的sql语句
        foreach ($arrData as $arr) {
            $values .= $flag ? '(' : ',(';
            foreach ($arr as $key => $value) {
                if ($flagV) {
                    if ($flag) $name .= "$key";
                    $values .= "'$value'";
                    $flagV = 0;
                } else {
                    if ($flag) $name .= ",$key";
                    $values .= ",'$value'";
                }
            }
            $values .= ') ';
            $flag = 0;
            $flagV = 1;
        }
    } else {
        //构建插入单条数据的sql语句
        foreach ($arrData as $key => $value) {
            if ($flagV) {
                $name = "$key";
                $values = "('$value'";
                $flagV = 0;
            } else {
                $name .= ",$key";
                $values .= ",'$value'";
            }
        }
        $values .= ") ";
    }

    $strSql = "replace into $table ($name) values $values";

    $ret = $dbh->exec($strSql);
    return $ret;

}

function http_get($value)
{
    $url = URL . $value;
    $ch = curl_init();
    $timeout = 60;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function format_html($html, $id)
{
    $result = '';
    if (empty($html)) {
        return $result;
    }


    $sub_str = "<table>";
    $sub_str_td = "您輸入的貨物追蹤查詢號碼如下";

    if (strpos($html, $sub_str)) {
        //位置开始后面的字符串
        $real_html = substr($html, 0, strpos($html, $sub_str));
        if (!empty($real_html) || strpos($real_html, '<tr>') != false) {
            $t1_html = substr($real_html, strpos($real_html, '<tr>'), (strlen($real_html) - strpos($real_html, '<tr>')));
            $t2_html = substr($t1_html, strpos($t1_html, '</tr>'), (strlen($t1_html) - strpos($t1_html, '</tr>')));
            //正则匹配
            $matchall = array();
            preg_match_all('/\<td.+?\>(.+?)\<\/td\>/', $t2_html, $matchall);

        }


        $string = strip_tags($matchall[0][0]);
        $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
        $nm[0] = trim($string);

        $string1 = strip_tags($matchall[0][1]);
        $string1 = htmlspecialchars($string1, ENT_QUOTES, 'UTF-8');
        $nm[1] = trim($string1);

        $string2 = strip_tags($matchall[0][2]);
        $string2 = htmlspecialchars($string2, ENT_QUOTES, 'UTF-8');
        $nm[2] = trim($string2);

        $string3 = strip_tags($matchall[0][3]);
        $string3 = htmlspecialchars($string3, ENT_QUOTES, 'UTF-8');
        $nm[3] = trim($string3);

        $result = $nm;

    } else if (strpos($html, $sub_str_td)) {
        //正在配送的状态
        $result = array($id, "未上线", "", "");
    } else {
        //非法的单号
        $result = array($id, "非法的单号", "", "");
    }

    return $result;
}


?>


<!DOCTYPE html >
<!--saved from url = (0044)http://ebiz.viewlayer.cn/detail/v2/791/c2/p8 -->
<html>
<head>
    <meta http - equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>黑猫宅急查询插件</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <LINK href="style/img/favicon.ico" type="image/x-icon" rel=icon>
    <script src="style/js/jquery.js"></script>

    <style>
        .title {
            text-align: center;
            font-size: 50px;
            margin-top: 80px;
            line-height: 10px;
            color: black;
        }

        .t1 {
            margin-top: 80px;
            margin-left: 100px;
        }

        .t2 {
            margin-top: 30px;
            margin-left: 100px;
        }

        .t3 {
            margin-top: 30px;
            margin-left: 100px;
        }

        .b1 {
            margin-top: 30px;
            margin-left: 100px;
        }

        .hid {
            display: none;
        }

        .tablelist {
            width: 80%;
            font-size: 20px;
            border: 1px solid #d0d0d0;
            line-height: 20px;
            text-align: center;
            margin-left: 10%;
            margin-right: 10%;
            border-spacing: 30px;
        }

        .top {
            width: 50px;
            height: 10px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body style=" background: #856d35 none repeat scroll 0 0;">
<div id="pagess">
    <a name="top"></a>

    <div class="title">
        黑猫宅急批量查询系统
    </div>
    <div class="price-item" style="margin-top: 80px;">

        <br/>
        <table cellpadding="0" cellspacing="0" class="tablelist">
            <tbody>
            <tr class="top" style="color: yellow;font-size: 25px">
                <td align="center">包裹查詢號碼</td>
                <td align="center">目前狀態</td>
                <td align="center">資料登入時間</td>
                <td align="center">負責營業所</td>
            </tr>

            <?php
            foreach ($nos as $nosig) {
                echo '<tr class="top">
                    <td align="center"><a href="#">' . $nosig[0] . '</a></td>
                    <td align="center">' . $nosig[1] . '</td>
                    <td align="center">' . $nosig[2] . '</td>
                    <td align="center">' . $nosig[3] . '</td>
                </tr>';
            }
            ?>
            </tbody>
        </table>
    </div>
</div>
